package com.pp.demo.module.auth.controller;

import com.pp.demo.common.constant.CommonErrorCode;
import com.pp.demo.common.constant.UserErrorCode;
import com.pp.demo.common.exception.BusinessException;
import com.pp.demo.common.response.Result;
import com.pp.demo.common.utils.JwtUtils;
import com.pp.demo.module.auth.param.LoginRequest;
import com.pp.demo.module.auth.param.RefreshTokenRequest;
import com.pp.demo.module.auth.service.CustomUserDetailsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

// 认证控制器 - 处理登录和令牌生成
@Api(tags = "鉴权")
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
class AuthController {
    private final JwtUtils jwtUtils;
    private final CustomUserDetailsService customUserDetailsService;
    private final PasswordEncoder passwordEncoder;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) throws Exception {
        // 验证系统凭据
        UserDetails userDetails = customUserDetailsService.loadUserByUsername(loginRequest.getSystemName());
        if (userDetails == null || !passwordEncoder.matches(loginRequest.getPassword(), userDetails.getPassword())) {
            log.warn("用户名或密码错误");
            throw new BusinessException(UserErrorCode.USER_INVALID);
        }

        // 生成令牌
        String systemId = "system_" + loginRequest.getSystemName();
        String accessToken = jwtUtils.generateAccessToken(systemId, loginRequest.getSystemName());
        String refreshToken = jwtUtils.generateRefreshToken(systemId);

        // 返回令牌
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("accessToken", accessToken);
        tokenMap.put("refreshToken", refreshToken);
        tokenMap.put("tokenType", "Bearer");

        return Result.success(tokenMap);
    }

    @ApiOperation("刷新令牌接口")
    @PostMapping("/refresh")
    public Result refreshToken(@RequestBody RefreshTokenRequest request) {
        String accessToken = request.getAccessToken();
        String refreshToken = request.getRefreshToken();

        String newAccessToken = jwtUtils.refreshToken(accessToken, refreshToken);
        if (newAccessToken != null) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("accessToken", newAccessToken);
            tokenMap.put("tokenType", "Bearer");
            return Result.success(tokenMap);
        }
        return Result.failure(CommonErrorCode.PERMISSION_DENIED);
    }
}
